<template>
  <div class="org-tree" :style="{ width: `${width}px` }">
    <!-- <a-input-search
      v-model:value="searchValue"
      @search="onSearch"
      class="org-search"
      placeholder="请输入"
    /> -->
    <a-tree
      class="tree-box"
      block-node
      :tree-data="gData"
      :load-data="onLoadData"
      :autoExpandParent="true"
      v-model:expandedKeys="expandedKeys"
      v-model:selectedKeys="selectedKeys"
      @select="onOrgelect"
    >
      <template #title="{ dataRef }">
        <div class="tree-item">
          <span class="item-title">{{ dataRef.title }}</span>
          <a-dropdown
            overlayClassName="tree-dropdown"
            :getPopupContainer="GetPopupContainer"
            placement="bottomRight"
            :trigger="['click']"
          >
            <a @click="(ev) => ev.stopPropagation()">
              <rb-icon class="item-more" type="icon-luoshu-more" />
            </a>
            <template #overlay>
              <a-menu @click="(menuInfo) => onActionSelect(menuInfo, dataRef)">
                <a-menu-item
                  v-for="it in TreeFolderActions"
                  :item="dataRef"
                  :key="it.key"
                >
                  {{ it.label }}
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </div>
      </template>
    </a-tree>
  </div>
  <tree-modal
    v-model:visible="visible"
    :type="curKey"
    :curItem="curItem"
    @onOk="onOk"
  ></tree-modal>
</template>

<script lang="ts">
import { defineComponent, ref, onBeforeMount, computed } from 'vue';
import { useStore } from 'vuex';
import { message, Modal } from 'ant-design-vue';
import {
  GetPopupContainer,
  GetUUID,
  ResponseHandle,
} from '@/global/util/preUtils';
import { TreeFolderActions } from '@/views/organization/constant';
import TreeModal from '@/views/organization/components/TreeModal.vue';

export default defineComponent({
  name: 'OrgTree',
  components: {
    TreeModal,
  },
  props: {
    width: {
      type: Number,
      default: 200,
    },
  },
  setup() {
    const store = useStore();
    const gData = ref<any>([]);
    const expandedKeys = ref<(string | number)[]>([]);
    const selectedKeys = computed({
      get: () => store.state.organization.selectedTreeKey,
      set: (val) => store.commit('organization/SetSelectedTreeKey', val),
    });
    const searchValue = ref<string>('');
    const visible = ref(false);
    const curKey = ref('');
    const curItem: any = ref({});

    const onSearch = (searchValue: string) => {};
    const onOrgelect = (keys: string[], ev: any) => {
      if (keys[0]) {
        store.dispatch('organization/getUserListByDept', {
          orgId: keys[0],
          setStore: true,
        });
      }
    };
    const onActionSelect = async (menuInfo: any, item: any) => {
      menuInfo.domEvent.stopPropagation();
      curKey.value = menuInfo.key;
      curItem.value = item;
      switch (menuInfo.key) {
        case 'create':
        case 'edit':
          visible.value = true;
          break;
        case 'remove':
          if (!curItem.value.parentKey) {
            return message.warning('根部门不可删除');
          }
          if (curItem.value.children?.length) {
            return message.warning('该部门下有成员，不可删除');
          }
          Modal.confirm({
            title: '确定删除?',
            content: '确定删除该部门，请确认!',
            async onOk() {
              const res = await store.dispatch(
                'organization/removeOrg',
                curItem.value.key,
              );
              ResponseHandle(res, () => {
                const parent: any = gData.value.find(
                  (it: any) => it.key === curItem.value.parentKey,
                );
                if (parent) {
                  parent.children = parent.children.filter(
                    (it: any) => it.key !== curItem.value.key,
                  );
                }
              });
            },
          });
          break;
        default:
          break;
      }
    };
    const onLoadData = async (treeNode: any) => {
      if (treeNode.dataRef.children) {
        return;
      }
      const res = await store.dispatch('organization/getOrgList', {
        parentId: treeNode.key,
      });
      ResponseHandle(res, () => {
        treeNode.dataRef.children = res.data.map((it: any) => {
          return {
            title: it.orgName,
            key: it.orgId,
            parentKey: treeNode.key,
            orgManage: it.orgManage,
          };
        });
        gData.value = [...gData.value];
      });
    };
    const onOk = async (data: { [key: string]: any }) => {
      const key = 'org_' + GetUUID();
      let res: any = {};
      switch (curKey.value) {
        case 'create':
          res = await store.dispatch('organization/createOrg', {
            parentId: data.parentId,
            orgId: key,
            orgName: data.orgName,
            orgManage: data.orgManage,
          });
          ResponseHandle(res, () => {
            !curItem.value.children && (curItem.value.children = []);
            curItem.value.children.push({
              title: data.orgName,
              key,
              parentKey: curItem.value.key,
              orgManage: data.orgManage,
            });
          });
          break;
        case 'edit':
          res = await store.dispatch('organization/savevOrg', {
            parentId: data.parentId,
            orgId: curItem.value.key,
            orgName: data.orgName,
            orgManage: data.orgManage,
          });
          ResponseHandle(res, () => (curItem.value.title = data.orgName));
          break;
        default:
          break;
      }
    };

    onBeforeMount(async () => {
      const res = await store.dispatch('organization/getOrgList', {
        parentId: 'root',
      });
      ResponseHandle(res, async () => {
        gData.value = res.data.map((it: any) => {
          return {
            title: it.orgName,
            key: it.orgId,
            parentKey: it.parentId,
            orgManage: it.orgManage,
          };
        });
        if (res.data[0]?.orgId) {
          store.dispatch('organization/getUserListByDept', {
            orgId: res.data[0].orgId,
            setStore: true,
          });
        }
        const firstKey = gData.value[0]?.key ?? '';
        expandedKeys.value = [firstKey];
        selectedKeys.value = [firstKey];
      });
    });

    return {
      visible,
      gData,
      expandedKeys,
      selectedKeys,
      searchValue,
      TreeFolderActions,
      curKey,
      curItem,
      GetPopupContainer,
      onSearch,
      onOrgelect,
      onActionSelect,
      onOk,
      onLoadData,
    };
  },
});
</script>

<style lang="less" scoped>
.org-tree {
  width: 200px;
  height: 100%;
  padding: 10px 0;
  border-right: 1px solid @rb-border-color-base;
  background-color: @rb-body-background;
  overflow-y: auto;
  transition: width 0.5s;
  .org-search {
    margin-bottom: 8px;
    padding: 0 8px;
  }
  :deep .tree-box {
    text-align: left;
    .tree-item {
      .flexRow();
      &:hover {
        .item-more {
          visibility: visible;
        }
      }
      .item-title {
        padding-left: 4px;
        display: inline-block;
        max-width: 115px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
      .item-more {
        visibility: hidden;
        // color: @rb-primary-color;
      }
    }
    .tree-dropdown {
      width: 100px;
    }
  }
}
</style>
